<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {
            height: 400px;
            border: solid;
            font-size: 3rem;
        }

        #top {
            width: 100px;
            height: 100px;
            background: gray;
            position: fixed;
            right: 30px;
            bottom: 100px;
            color: white;
            justify-content: center;
            align-items: center;
            display: flex;
            font-size: 3rem;
            cursor: pointer;
        }
    </style>

</head>

<body>

    <div id="top" style="display: none;">TOP</div>

    <div id="content">
        <p>p1</p>
        <!-- <p>p2</p>
        <p>p3</p>
        <p>p4</p>
        <p>p5</p>
        <p>p6</p> -->
    </div>

    <script>
        // 优化页面性能（内容懒加载）
        const content = document.getElementById('content');
        const wtop = document.getElementById('top');

        //初始换页面，插入新内容，直到出现滚动
        while (true) {
            // 创建新内容
            const p = document.createElement('p');
            p.innerHTML = 'new content'
            content.append(p);
            // 判断页面内容的高度>窗口高度，结束内容创建
            if (document.documentElement.scrollHeight > window.innerHeight) {
                break;
            }
        }

        wtop.onclick = function () {
            // window.scrollTo(0, 0);
            // 平滑滚动
            window.scrollTo({
                top: 0, // y
                left: 0, // x
                behavior: "smooth"
            })
        }
        // 窗口滚动事件
        window.onscroll = function () {
            // 计算窗口滚动是否触底
            const dis = document.documentElement.scrollHeight - window.pageYOffset - window.innerHeight;
            if (dis < 40) {
                const p = document.createElement('p');
                p.innerHTML = 'new content'
                content.append(p);
            }
            // 计算什么时候出现TOP
            if (window.pageYOffset > window.innerHeight) {
                wtop.style.display = '';
            } else {
                wtop.style.display = 'none';
            }
        }

    </script>

</body>

</html>